using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Runtime.Serialization;
using System.Xml;
using System.Xml.Serialization;

namespace Bookvar.Common
{
    /// <summary>
    /// Summary description for Serializer.
    /// </summary>
    public static class Serializer
    {
        public static string Serialize( object valueToSerialize )
        {
            var serializedObject = new StringWriter( CultureInfo.InvariantCulture );
            XmlWriter xmlWriter = new XmlTextWriter( serializedObject );

            var serializer = new DataContractSerializer( valueToSerialize.GetType() );
            serializer.WriteObject( xmlWriter, valueToSerialize );

            return serializedObject.ToString();
        }

        [SuppressMessage( "Microsoft.Design",
            "CA1004:GenericMethodsShouldProvideTypeParameter" )]
        public static T Deserialize<T>( string serializedObject ) where T : class
        {
            var reader = new StringReader( serializedObject );
            XmlReader xmlReader = new XmlTextReader( reader );

            try
            {
                var serializer = new DataContractSerializer( typeof ( T ) );
                return serializer.ReadObject( xmlReader ) as T;
            }
            catch ( SerializationException )
            {
                var serializer = new XmlSerializer( typeof ( T ) );
                return serializer.Deserialize( xmlReader ) as T;
            }
        }
    }
}